package com.cruise.game.service.impl.order;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cruise.game.common.api.ApiException;
import com.cruise.game.common.constants.OrderConstants;
import com.cruise.game.common.enums.OrderStatusEnum;
import com.cruise.game.mapper.*;
import com.cruise.game.model.entity.*;
import com.cruise.game.model.param.order.AfterSalesParam;
import com.cruise.game.model.param.order.CreateOrderParam;
import com.cruise.game.model.param.order.RateOrderParam;
import com.cruise.game.model.vo.common.PageResult;
import com.cruise.game.model.vo.order.OrderDetailVO;
import com.cruise.game.model.vo.order.OrderListVO;
import com.cruise.game.service.order.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 订单服务实现
 * 
 * @author cruise
 * @date 2025-02-28
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private OrderRatingMapper orderRatingMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private AgentMapper agentMapper;

    @Resource
    private GameServiceMapper gameServiceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderCreationResult createOrder(CreateOrderParam param, Long userId) {
        // 验证用户是否存在
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ApiException("用户不存在");
        }

        // 验证服务是否存在
        GameService gameService = gameServiceMapper.selectById(param.getServiceId());
        if (gameService == null || !"active".equals(gameService.getStatus())) {
            throw new ApiException("服务不存在或已下架");
        }

        // 查询余额是否充足
        BigDecimal price = gameService.getPrice();
        if (user.getBalance().compareTo(price) < 0) {
            throw new ApiException("余额不足");
        }

        // 构建订单对象
        Order order = new Order();
        order.setOrderNumber(generateOrderNumber());
        order.setUserId(userId);
        order.setServiceId(param.getServiceId());
        order.setPrice(price);
        order.setAccountType(param.getAccountType());
        order.setAccountUsername(param.getAccountUsername());
        order.setAccountPassword(param.getAccountPassword());
        order.setTaskDescription(param.getTaskDescription());
        order.setExpectedCompletionTime(param.getExpectedCompletionTime());
        order.setStatus(OrderConstants.ORDER_STATUS_PENDING);

        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        order.setOrderedAt(now);
        order.setCreatedAt(now);
        order.setUpdatedAt(now);

        // 保存订单
        orderMapper.insert(order);

        // 更新用户余额
        userMapper.updateBalance(userId, price.negate());

        // 返回订单创建结果
        return new OrderCreationResult(order.getId(), order.getOrderNumber(), order.getPrice());
    }

    @Override
    public PageResult<OrderListVO> getUserOrderList(Long userId, String status, Integer page, Integer pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId);
        if (StringUtils.isNotBlank(status) && !"all".equals(status)) {
            queryWrapper.eq(Order::getStatus, status);
        }
        queryWrapper.orderByDesc(Order::getCreatedAt);

        // 分页查询
        Page<Order> pageParam = new Page<>(page, pageSize);
        IPage<Order> orderPage = orderMapper.selectPage(pageParam, queryWrapper);

        // 转换为VO
        List<OrderListVO> orderVOs = convertToOrderListVOs(orderPage.getRecords());

        // 返回分页结果
        return PageResult.of(orderVOs, orderPage.getTotal(), page, pageSize);
    }

    @Override
    public OrderDetailVO getUserOrderDetail(Long orderId, Long userId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new ApiException("无权查看此订单");
        }

        // 构建订单详情VO
        return buildOrderDetailVO(order);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean cancelOrder(Long orderId, Long userId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderStatusEnum.canCancel(order.getStatus())) {
            throw new ApiException("当前订单状态不可取消");
        }

        // 更新订单状态
        order.setStatus(OrderConstants.ORDER_STATUS_CANCELLED);
        order.setUpdatedAt(LocalDateTime.now());
        orderMapper.updateById(order);

        // 退还用户余额
        userMapper.updateBalance(userId, order.getPrice());

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean confirmOrder(Long orderId, Long userId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderStatusEnum.canConfirm(order.getStatus())) {
            // 提供更明确的错误信息，包括当前状态
            OrderStatusEnum currentStatus = OrderStatusEnum.getByValue(order.getStatus());
            String statusDesc = currentStatus != null ? currentStatus.getDesc() : order.getStatus();
            throw new ApiException("当前订单状态为'" + statusDesc + "'，不可确认完成。只有处于'已完成'状态的订单才能确认");
        }

        // 获取代理信息
        Long agentId = order.getAgentId();
        if (agentId == null) {
            throw new ApiException("订单未分配代理");
        }
        Agent agent = agentMapper.selectById(agentId);
        if (agent == null) {
            throw new ApiException("代理不存在");
        }

        // 更新订单状态
        // 修改: 使用updateById而不是updateStatus
        order.setStatus(OrderConstants.ORDER_STATUS_COMPLETED);
        order.setUpdatedAt(LocalDateTime.now());
        orderMapper.updateById(order);

        // 更新代理已完成订单数
        agentMapper.updateOrdersCompleted(agentId, 1);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean applyAfterSales(Long orderId, AfterSalesParam param, Long userId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderStatusEnum.canAfterSales(order.getStatus())) {
            throw new ApiException("当前订单状态不可申请售后");
        }

        // 更新订单状态
        // 修改: 使用updateById而不是updateStatus
        order.setStatus(OrderConstants.ORDER_STATUS_AFTER_SALES);
        order.setUpdatedAt(LocalDateTime.now());
        orderMapper.updateById(order);

        // TODO: 记录售后申请信息

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean rateOrder(Long orderId, RateOrderParam param, Long userId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getUserId(), userId)) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderStatusEnum.canRate(order.getStatus())) {
            throw new ApiException("当前订单状态不可评价");
        }

        // 验证是否已评价
        OrderRating existingRating = orderRatingMapper.selectByOrderId(orderId);
        if (existingRating != null) {
            throw new ApiException("订单已评价，不可重复评价");
        }

        // 获取代理信息
        Long agentId = order.getAgentId();
        if (agentId == null) {
            throw new ApiException("订单未分配代理");
        }

        // 创建评价
        OrderRating rating = new OrderRating();
        rating.setOrderId(orderId);
        rating.setUserId(userId);
        rating.setAgentId(agentId);
        rating.setRating(param.getRating());
        rating.setComment(param.getComment());
        rating.setCreatedAt(LocalDateTime.now());
        orderRatingMapper.insert(rating);

        // 更新代理评分
        BigDecimal averageRating = orderRatingMapper.selectAgentAverageRating(agentId);
        if (averageRating != null) {
            agentMapper.updateRating(agentId, averageRating);
        }

        return true;
    }

    @Override
    public PageResult<OrderListVO> getPendingOrders(Long gameCategoryId, Integer page, Integer pageSize) {
        // 获取待接单列表
        List<Order> pendingOrders = orderMapper.selectPendingOrders(gameCategoryId, page * pageSize);

        // 提取分页数据
        int start = (page - 1) * pageSize;
        int end = Math.min(start + pageSize, pendingOrders.size());
        List<Order> pageOrders = pendingOrders.subList(start, end);

        // 转换为VO
        List<OrderListVO> orderVOs = convertToOrderListVOs(pageOrders);

        // 返回分页结果
        return PageResult.of(orderVOs, pendingOrders.size(), page, pageSize);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean acceptOrder(Long orderId, Long agentId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证订单状态
        if (!OrderStatusEnum.canAccept(order.getStatus())) {
            throw new ApiException("当前订单状态不可接单");
        }

        // 验证代理是否存在
        Agent agent = agentMapper.selectById(agentId);
        if (agent == null) {
            throw new ApiException("代理不存在");
        }

        // 查询服务信息
        GameService gameService = gameServiceMapper.selectById(order.getServiceId());
        if (gameService == null) {
            throw new ApiException("服务不存在");
        }

        // 验证代理可接此类订单
        if (!Objects.equals(agent.getGameCategoryId(), gameService.getCategoryId())) {
            throw new ApiException("不能接这类游戏的订单");
        }

        // 更新订单信息
        LocalDateTime now = LocalDateTime.now();
        order.setAgentId(agentId);
        order.setStatus(OrderConstants.ORDER_STATUS_IN_PROGRESS);
        order.setAcceptedAt(now);
        order.setUpdatedAt(now);
        orderMapper.updateById(order);

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean startService(Long orderId, Long agentId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getAgentId(), agentId)) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderConstants.ORDER_STATUS_IN_PROGRESS.equals(order.getStatus())) {
            throw new ApiException("当前订单状态不正确");
        }

        // 订单已经是进行中状态，无需更新

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean completeService(Long orderId, String completionImageUrl, Long agentId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getAgentId(), agentId)) {
            throw new ApiException("无权操作此订单");
        }

        // 验证订单状态
        if (!OrderStatusEnum.canComplete(order.getStatus())) {
            throw new ApiException("当前订单状态不可完成");
        }

        // 更新订单信息
        LocalDateTime now = LocalDateTime.now();
        order.setStatus(OrderConstants.ORDER_STATUS_COMPLETED);
        order.setCompletedAt(now);
        order.setCompletionImageUrl(completionImageUrl);
        order.setUpdatedAt(now);
        orderMapper.updateById(order);

        return true;
    }

    @Override
    public PageResult<OrderListVO> getAgentOrderList(Long agentId, String status, Integer page, Integer pageSize) {
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getAgentId, agentId);
        if (StringUtils.isNotBlank(status) && !"all".equals(status)) {
            queryWrapper.eq(Order::getStatus, status);
        }
        queryWrapper.orderByDesc(Order::getCreatedAt);

        // 分页查询
        Page<Order> pageParam = new Page<>(page, pageSize);
        IPage<Order> orderPage = orderMapper.selectPage(pageParam, queryWrapper);

        // 转换为VO
        List<OrderListVO> orderVOs = convertToOrderListVOs(orderPage.getRecords());

        // 返回分页结果
        return PageResult.of(orderVOs, orderPage.getTotal(), page, pageSize);
    }

    @Override
    public OrderDetailVO getAgentOrderDetail(Long orderId, Long agentId) {
        // 查询订单
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new ApiException("订单不存在");
        }

        // 验证权限
        if (!Objects.equals(order.getAgentId(), agentId)) {
            throw new ApiException("无权查看此订单");
        }

        // 构建订单详情VO
        return buildOrderDetailVO(order);
    }

    @Override
    public List<RecentOrderVO> getRecentOrders(int limit) {
        // 查询最近订单 - 修改为正确的类型
        List<Map<String, Object>> recentOrderMaps = orderMapper.selectRecentOrders(limit);

        // 转换为VO
        List<RecentOrderVO> recentOrderVOs = new ArrayList<>();
        for (Map<String, Object> orderMap : recentOrderMaps) {
            // 提取数据
            Long userId = getLongValue(orderMap, "user_id");
            Long serviceId = getLongValue(orderMap, "service_id");
            LocalDateTime orderedAt = getDateTimeValue(orderMap, "ordered_at");

            // 获取用户信息
            User user = userId != null ? userMapper.selectById(userId) : null;

            // 获取服务信息
            GameService gameService = serviceId != null ? gameServiceMapper.selectById(serviceId) : null;

            // 计算时间差
            String timeAgo = calculateTimeAgo(orderedAt);

            // 创建VO
            RecentOrderVO vo = new RecentOrderVO(
                    user != null ? user.getNickname() : (String) orderMap.get("userNickname"),
                    gameService != null ? gameService.getName() : (String) orderMap.get("serviceName"),
                    timeAgo);
            recentOrderVOs.add(vo);
        }

        return recentOrderVOs;
    }

    // 辅助方法 - 从Map中获取Long类型值
    private Long getLongValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        return null;
    }

    // 辅助方法 - 从Map中获取DateTime类型值
    private LocalDateTime getDateTimeValue(Map<String, Object> map, String key) {
        Object value = map.get(key);
        if (value instanceof LocalDateTime) {
            return (LocalDateTime) value;
        } else if (value instanceof String) {
            try {
                return LocalDateTime.parse((String) value);
            } catch (Exception e) {
                log.error("解析日期时间失败: {}", e.getMessage(), e);
            }
        }
        return null;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNumber() {
        // 格式: ORD + 年月日 + 4位序号
        String prefix = "ORD" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 获取当天最后一个订单编号
        String lastOrderNumber = orderMapper.selectLastOrderNumber();

        // 计算新序号
        int sequence = 1;
        if (lastOrderNumber != null && lastOrderNumber.startsWith(prefix)) {
            try {
                sequence = Integer.parseInt(lastOrderNumber.substring(prefix.length())) + 1;
            } catch (NumberFormatException e) {
                log.error("解析订单编号序号失败: {}", e.getMessage(), e);
            }
        }

        // 返回新订单编号
        return prefix + String.format("%04d", sequence);
    }

    /**
     * 计算时间差
     */
    private String calculateTimeAgo(LocalDateTime dateTime) {
        if (dateTime == null) {
            return "未知时间";
        }

        LocalDateTime now = LocalDateTime.now();
        Duration duration = Duration.between(dateTime, now);

        long seconds = duration.getSeconds();
        if (seconds < 60) {
            return seconds + "秒前";
        }

        long minutes = seconds / 60;
        if (minutes < 60) {
            return minutes + "分钟前";
        }

        long hours = minutes / 60;
        if (hours < 24) {
            return hours + "小时前";
        }

        long days = hours / 24;
        if (days < 30) {
            return days + "天前";
        }

        long months = days / 30;
        if (months < 12) {
            return months + "个月前";
        }

        return days / 365 + "年前";
    }

    /**
     * 转换为订单列表VO
     */
    private List<OrderListVO> convertToOrderListVOs(List<Order> orders) {
        if (orders == null || orders.isEmpty()) {
            return new ArrayList<>();
        }

        return orders.stream().map(order -> {
            OrderListVO vo = new OrderListVO();
            BeanUtils.copyProperties(order, vo);

            // 获取服务名称
            GameService gameService = gameServiceMapper.selectById(order.getServiceId());
            if (gameService != null) {
                vo.setServiceName(gameService.getName());
            }

            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 构建订单详情VO
     */
    private OrderDetailVO buildOrderDetailVO(Order order) {
        OrderDetailVO vo = new OrderDetailVO();
        BeanUtils.copyProperties(order, vo);

        // 获取服务名称
        GameService gameService = gameServiceMapper.selectById(order.getServiceId());
        if (gameService != null) {
            vo.setServiceName(gameService.getName());
        }

        // 设置用户信息
        User user = userMapper.selectById(order.getUserId());
        if (user != null) {
            OrderDetailVO.UserInfo userInfo = new OrderDetailVO.UserInfo();
            userInfo.setId(user.getId());
            userInfo.setNickname(user.getNickname());
            vo.setUser(userInfo);
        }

        // 设置代理信息
        if (order.getAgentId() != null) {
            Agent agent = agentMapper.selectById(order.getAgentId());
            if (agent != null) {
                OrderDetailVO.AgentInfo agentInfo = new OrderDetailVO.AgentInfo();
                agentInfo.setId(agent.getId());

                User agentUser = userMapper.selectById(agent.getUserId());
                if (agentUser != null) {
                    agentInfo.setNickname(agentUser.getNickname());
                }

                vo.setAgent(agentInfo);
            }
        }

        // 设置评价信息
        OrderRating rating = orderRatingMapper.selectByOrderId(order.getId());
        if (rating != null) {
            OrderDetailVO.RatingInfo ratingInfo = new OrderDetailVO.RatingInfo();
            ratingInfo.setId(rating.getId());
            ratingInfo.setRating(rating.getRating());
            ratingInfo.setComment(rating.getComment());
            ratingInfo.setCreatedAt(rating.getCreatedAt());
            vo.setRating(ratingInfo);
        }

        return vo;
    }
}